/**
 * Created by djh on 2016/11/17.
 * 资讯js
 *
 */

define(function(require,exports){
   var common = require("common");

   /**
    * 幻灯焦点广告
    * @param {$} $obj 幻灯广告对象
    * @param {String} [speed="slow"] 幻灯广告切换速度
    * @param {String} [autoTime=3000] 幻灯广告停留时间
    * @example
    *      common.focusSlide($("#focusSlide"));
    * */
   exports.focusSlide = function($obj,speed,autoTime){
      var speed=speed || "slow";
      var autoTime=autoTime || 5000;
      var currentindex=0;
      var length=$obj.find(".item").length;
      if(length<2){
         $obj.find(".item").show();
         return;
      }
      //按钮导航
      var $btns=$('<div class="btns"></div>');
      var btnHtml='';
      for(var i=0; i<length; i++){
         btnHtml += '<a href="javascript:;">'+(i+1)+'</a>';
      }
      $btns.html(btnHtml);
      $obj.append($btns);
      var $item=$obj.find(".item");
      var $btn=$btns.find("a");
      $item.eq(currentindex).show();
      $btn.eq(currentindex).addClass("on");

      //切换
      var fn = function(index){
         $item.hide();
         $btn.removeClass("on");
         $item.eq(index).stop().fadeIn(speed);
         $btn.eq(index).addClass("on");
      };

      //设置上一个背景（解决切换时有空白出现）
      var setBg = function(index){
         var url=$item.eq(index).find("img").attr("src");
         $obj.find(".wrap").css({"background":"url("+url+") no-repeat center 0"});
      };
      /*下一个*/
      var prevFn=function(){
         setBg(currentindex);
         currentindex--;
         if(currentindex<0){
            currentindex=length-1;
         }
         fn(currentindex);
      };

      /*下一个*/
      var nextFn=function(){
         setBg(currentindex);
         currentindex++;
         if(currentindex==length){
            currentindex=0;
         }
         fn(currentindex);
      };

      //手动点击
      $obj.find(".btns a").each(function(index, element) {
         $(this).on("click",function(){
            currentindex=index;
            fn(index);
         });
      });

      //添加arrows 左右点击
      $obj.find(".arrow .left").on("click",function(){
         prevFn(currentindex);
      });
      $obj.find(".arrow .right").on("click",function(){
         nextFn(currentindex);
      });

      //自动播放
      var timer=setInterval(nextFn, autoTime);
      $obj.on({
         mouseenter:function(){
            clearInterval(timer);
         },
         mouseleave:function(){
            timer=setInterval(nextFn, autoTime);
         }
      });
   };

   exports.indexInit = function(){
      common.topMenu(2);
      //注册slide
      exports.focusSlide($("#focusSlide"));
   }

});

